export class DrownTool {
  constructor (arg) {
    this.entityPolygon = null
    this.points = null
    this.drawingMode = 'polygon'
    this.activeShapePoints = []
    this.activeShape = undefined
    this.floatingPoint = undefined
    this.viewer = arg.viewer
    this.Cesium = arg.Cesium
    this.entities = arg.viewer.dataSourceDisplay._defaultDataSource.entities
    this.scene = arg.viewer.cesiumViewer.scene
    this.handler = null
    this.entity = null
    this.currentHeight = null
    this.maxValue = null
    this.interval = null
    this._polygon = null //活动面
    this._polygonLast = null //最后一个面
    this._entities_point = [] //脏数据
    this._entities_polygon = [] //脏数据
    this._polygonData = null //用户构造面
    this.addInter = 1
    this.extrudedHeight = 0
  }

  createPoint (position) {
    let point = this.entities.add({
      position: position,
      point: {
        pixelSize: 10,
        color: this.Cesium.Color.YELLOW,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        heightReference: this.Cesium.HeightReference.CLAMP_TO_GROUND
      }
    })
    this.points = point
    return point
  }
  //创建面
  createPolygon() {
    let that = this
    let polygon = this.entities.add({
      polygon: {
        hierarchy: new that.Cesium.CallbackProperty(function () {
          return new that.Cesium.PolygonHierarchy(that.activeShapePoints)
        }, false),
        // clampToGround: true,
        show: true,
        material: new this.Cesium.ColorMaterialProperty(this.Cesium.Color.LIGHTSKYBLUE.withAlpha(0.7)),
        width: 3,
        // outlineColor: that.Cesium.Color.fromCssColorString(option.outLineColor),
        // outlineWidth: 10,
        // fill: option.flag,
        // outline: !option.flag
      }
    })
    that._entities_polygon.push(polygon)
    return polygon
  }
  //加载面
  loadPolygon(data) {
    let that = this
   
    let polygon = ""
    polygon = this.entities.add({
      polygon: {
        hierarchy: new that.Cesium.PolygonHierarchy(data),
        // clampToGround: true,
        show: true,
        // fill: option.flag,
        material: new this.Cesium.ColorMaterialProperty(this.Cesium.Color.LIGHTSKYBLUE.withAlpha(0.7)),
        width: 3,
        // outlineColor: that.Cesium.Color.fromCssColorString(option.outLineColor),
        // outlineWidth: 30,
        // outline: !option.flag
      }
    })
    return polygon;
  }
  init () {
    let that = this
    this.handler = new this.Cesium.ScreenSpaceEventHandler(this.scene.canvas)
    this.handler.setInputAction(function (event) {
      
      if (!that.Cesium.Entity.supportsPolylinesOnTerrain(that.scene)) {
        console.log('this browser does not support polylines on terrain.');
        return
      }
      let earthPosition = that.scene.pickPosition(event.position)
      if (that.Cesium.defined(earthPosition)) {
        if (that.activeShapePoints.length === 0) {
          that.activeShapePoints.push(earthPosition)
        }
        
        that.activeShapePoints.push(earthPosition)
        that.createPoint(earthPosition)
      }
    }, that.Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (event) {
      if (that.activeShapePoints.length < 1) return
      let newPosition = that.scene.pickPosition(event.endPosition)
      if (that.activeShapePoints.length == 3) {
        if (!that.Cesium.defined(that._polygon)) {

          that._polygon = that.createPolygon()
        }
      }
      that.activeShapePoints.pop()
      that.activeShapePoints.push(newPosition)
    }, that.Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    this.handler.setInputAction(function (event) {
      if (!that._polygon) return
      let newPosition = that.scene.pickPosition(event.position)
      if (!newPosition) return
      that.activeShapePoints.pop()
      that.activeShapePoints.push(newPosition)
      that.createPoint(newPosition)
      that._polygonData = that.activeShapePoints.concat()
      that.entities.remove(that.activeShapePoints) //移除
      that._polygon = null
      that.activeShapePoints = []
      let Polygon = that.loadPolygon(that._polygonData)
      that._entities_polygon.push(Polygon)
      that._polygonLast = Polygon
      that.handler.removeInputAction(that.Cesium.ScreenSpaceEventType.LEFT_CLICK)
      that.handler.removeInputAction(that.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      that.handler.removeInputAction(that.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      that.drawOk(that._polygonLast)
      
    }, that.Cesium.ScreenSpaceEventType.RIGHT_CLICK)


  }
  
  drawOk (entity) {
    this.entity = entity
    let that = this
    let t = this.computePolygonHeightRange(entity.polygon.hierarchy.getValue())
    this.currentHeight = t.minHeight
    this.maxValue = t.maxHeight
    this.startFx(this.currentHeight)
    this.interval = setInterval(function () {
      
      that.currentHeight > that.maxValue ? that.stopFx() : that.updateHeight()
    }, 500)
  }
  
  stopFx () {
    if (this.interval) {
      clearInterval(this.interval)
      this.interval = null
    }
    
  }
  computePolygonHeightRange (_data) {
    let t = []
    let data = _data.positions
    for (let i = 0; i < data.length; i++) {
      t.push(data[i].clone())
    }
    let h = 0
    let g = 0
    let c = Math.PI / 32
    // let polygon = this.Cesium.PolygonGeometry.fromPositions({
    //   positions: this.Cesium.Cartesian3.fromDegreesArray([-72,40, -70, 35, -75, 30, -70, 30, -68, 40])
    // })
    // let geometry = this.Cesium.PolygonGeometry.createGeometry(polygon)
    // console.log('成功创建', geometry);
    let m = this.Cesium.PolygonGeometry.fromPositions({
      positions: t,
      vertexFormat: this.Cesium.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT,
      granularity: c
    })
    let d = this.Cesium.PolygonGeometry.createGeometry(m)
    console.log('创建成功', d);
    let a
    let n
    let r
    let o
    let s
    let u
    let l
    for (let i = 0; i < d.indices.length; i += 3) {
      a = d.indices[i],
      n = d.indices[i + 1]
      r = d.indices[i + 2]
      l = new this.Cesium.Cartesian3(d.attributes.position.values[3 * a], d.attributes.position.values[3 * a + 1], d.attributes.position.values[3 * a + 2])
      o = this.scene.globe.getHeight(this.Cesium.Cartographic.fromCartesian(l))
      if (o < g) {
        g = o
      }
      if (o > h) {
        h = o
      }
      l = new this.Cesium.Cartesian3(d.attributes.position.values[3 * n], d.attributes.position.values[3 * n + 1], d.attributes.position.values[3 * n + 2])
      s = this.scene.globe.getHeight(this.Cesium.Cartographic.fromCartesian(l))
      if (s < g) {
        g = s
      }
      if (s > h) {
        h = s
      }
      l = new this.Cesium.Cartesian3(d.attributes.position.values[3 * r], d.attributes.position.values[3 * r + 1], d.attributes.position.values[3 * r + 2])
      u = this.scene.globe.getHeight(this.Cesium.Cartographic.fromCartesian(l))
      if (u < g) {
        g = u
      }
      if (u > h) {
        h = u
      }
    }
    this.addInter = (h - g) / 20
    return {
      maxHeight: h,
      minHeight: g
    }
  }
  startFx (e) {
    this.scene.globe.depthTestAgninstTerrain = true
    let that = this
    this.extrudedHeight = e
    this.entity.polygon.extrudedHeight = new this.Cesium.CallbackProperty(function (e) {
      return that.extrudedHeight
    }, false)
    let a = []
    
    let i = this.entity.polygon.hierarchy.getValue()
    i = i.positions
    for (let n = 0; n < i.length; n++) {
      let r = this.Cesium.Ellipsoid.WGS84.cartesianToCartographic(i[n])
      let o = {
        lon: this.Cesium.Math.toDegrees(r.longitude),
        lat: this.Cesium.Math.toDegrees(r.latitude),
        hgt: e
      }
      let s = [o.lon, o.lat, o.hgt]
      a = a.concat(s)
    }
    let res = this.Cesium.Cartesian3.fromDegreesArrayHeights(a)
    // this.entity.polygon.hierarchy = new this.Cesium.CallbackProperty(function (e) {
    //   return res
    // }, false)
  }
  clear () {
    this.scene.globe.depthTestAgainstTerrain = false
    this.entity = null
  }
  updateHeight () {
    this.entity.polygon.extrudedHeight = this.currentHeight
    this.currentHeight  = this.currentHeight + this.addInter
  }
  
}

export default DrownTool
